let adConfig = [
    ["广告1", "广告2", "广告3", "广告4"]
]

function initExportAdSelect() {
    let exportList = localStorage.getItem("ad-export-select") || "[]";
    exportList = JSON.parse(exportList);
    if(exportList.length == 0) return;
    const selectElement = document.getElementById("ad-export-select");
    selectElement.innerHTML = "";
    for (let i = 0; i < exportList.length; i++) {
      const exportInfo = exportList[i];
      const newOption = document.createElement("option");
      // newOption.value = JSON.stringify(exportInfo);
      newOption.selected = i == exportList.length - 1;
      let exportDate = new Date(exportInfo.time);
      newOption.textContent = `${exportDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`;
      selectElement.appendChild(newOption);
    }
    adConfig = exportList[exportList.length - 1].config;
    selectElement.addEventListener("change", onExportAdSelectChanged);
  }

  function onExportAdSelectChanged() {
    let localExportList = localStorage.getItem("ad-export-select") || "[]";
    localExportList = JSON.parse(localExportList);
    const selectElement = document.getElementById("ad-export-select");
    const selectedIndex = selectElement.selectedIndex;
    if(selectedIndex == -1) {
      return 
    }
    adConfig = localExportList[selectedIndex].config;
    updateAdList();
  }

function updateAdList() {
    var ad_level_list = document.getElementById("ad-level-list");
    if(currentSelectOrderGroupIndex < 0){
        ad_level_list.innerHTML = "";
        return;
    }
    if (ad_level_list.innerHTML == "") {
        initAdList();
    }
    ad_level_list.innerHTML = "";
    let currentAdList = adConfig[currentSelectOrderGroupIndex];
    if(!currentAdList || currentAdList.length == 0) {
        return;
    }
    for (let i = 0; i < currentAdList.length; i++) {
        const Adid = currentAdList[i];
        const listItem = document.createElement("li");
        listItem.style = "display: flex;flex-direction: row;";
        listItem.setAttribute("data-index", i);
        listItem.setAttribute("data-item", Adid);

        //广告ID
        const label = document.createElement("dev");
        label.className = "level-title";
        label.textContent = Adid;
        label.style.pointerEvents = "none";
        listItem.appendChild(label);

        // const div = document.createElement("div");
        // div.style.flex = 1;
        // div.style.pointerEvents = "none";
        // listItem.appendChild(div);
        ad_level_list.appendChild(listItem);
    }
}

let adListInited = false;
function initAdList() {
    if(adListInited){
        return;
    }
    adListInited = true;

    let sortable_list = document.getElementById("ad-level-list")
    new Sortable(sortable_list, {
        group: 'ad',
        pull: false,
        put: false,
        sort: false,
    });

    sortable_list.addEventListener('click', function (event) {
        const target = event.target;
        if (target.tagName === 'LI') {
            target.classList.toggle('li-selected');
            sortable_list.focus();
        }
    });

    sortable_list.addEventListener('keydown', function (event) {
        if(event.target != sortable_list){
            return;
        }
        const keyCode = event.keyCode || event.which;
        if (keyCode === 46 || keyCode === 8) {
            // 获取选中的项
            const listItems = document.querySelectorAll("#ad-level-list li");
            const selectedItems = Array.from(listItems).filter(item => item.classList.contains('li-selected'));
            selectedItems.forEach(item => item.remove());
            onAdDelete();
        }
    });
}

function onAdDelete() {
    let currentAdList = adConfig[currentSelectOrderGroupIndex];
    currentAdList.length = 0;
    const listItems = document.querySelectorAll("#ad-level-list li");
    for (let i = 0; i < listItems.length; i++) {
        const element = listItems[i];
        let id = element.getAttribute("data-item");
        currentAdList.push(id);
    }
}

function onAddAd() {
    let adId = document.getElementById('ad-id-input').value;
    if(!adId){
        showToast("请输入广告ID");
        return
    }
    let currentAdList = adConfig[currentSelectOrderGroupIndex] = adConfig[currentSelectOrderGroupIndex] || [];
    let hasExist = currentAdList.filter(value=>value==adId);
    if(hasExist && hasExist.length){
        showToast("有重复的广告："+ adId);
        return
    }
    currentAdList.push(adId);
    updateAdList();
}

function exportAdData() {
    console.log("打印最新推荐配置:", adConfig);
    
    
    let jsonString = JSON.stringify(adConfig);
    const dataURL = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);
    
    const a = document.createElement('a');
    a.href = dataURL;
    let flag = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    flag = flag.replace(/:/g, ".").replace(/\//g, ".").replace(" ", "_")
    // let md5 = saveLevelOrderToLocal();
    a.download = `ad_${flag}.json`;
    a.click();
    a.remove();
    jsonString = jsonString.replace(/"/g, "'");
    navigator.clipboard.writeText(`广告关联:${flag}\n${jsonString}`);
    saveToLocal();
    initExportAdSelect();
    showToast("成功！配置已拷贝到粘贴贴面板, Ctrl+V发送给程序。");
}

function saveToLocal() {
    let exportList = localStorage.getItem("ad-export-select") || "[]";
    exportList = JSON.parse(exportList);
    exportList.push({time:Date.now(), config:adConfig});
    if(exportList.length > 10){
        exportList.splice(0, 10-exportList.length)
    }
    localStorage.setItem("ad-export-select", JSON.stringify(exportList));
}

function importAdData() {
    const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = function (event) {
          const jsonStr = event.target.result;
          fileInput.remove();
          const jsonData = JSON.parse(jsonStr);
          console.log("导入：", jsonData);
          adConfig = jsonData;
          updateAdList();
          showToast("数据导入成功!");
        };
        reader.readAsText(file);
      });
      fileInput.click();
}